<template>
  <div class="permission-list-container">
    <div class="page-header">
      <h2>权限管理</h2>
      <el-button type="primary" @click="handleAdd">添加权限</el-button>
    </div>

    <el-card>
      <el-table :data="permissionList" border style="width: 100%" v-loading="loading" row-key="id" default-expand-all>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="权限名称" width="180" />
        <el-table-column prop="code" label="权限编码" width="180" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{row}">
            <el-tag :type="row.type === 'menu' ? 'primary' : row.type === 'button' ? 'success' : 'info'">
              {{ row.type === 'menu' ? '菜单' : row.type === 'button' ? '按钮' : '目录' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" width="180" />
        <el-table-column prop="component" label="组件" width="180" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{row}">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleAddChild(row)" v-if="row.type !== 'button'">添加子项</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="getDialogTitle()"
      width="600px"
    >
      <el-form :model="permissionForm" label-width="100px" :rules="rules" ref="permissionFormRef">
        <el-form-item label="上级权限">
          <el-cascader
            v-model="permissionForm.parentId"
            :options="permissionOptions"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            clearable
            placeholder="请选择上级权限"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="permissionForm.code" placeholder="请输入权限编码" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型" style="width: 100%">
            <el-option label="目录" value="directory" />
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
          </el-select>
        </el-form-item>
        <el-form-item label="路径" prop="path" v-if="permissionForm.type !== 'button'">
          <el-input v-model="permissionForm.path" placeholder="请输入路径" />
        </el-form-item>
        <el-form-item label="组件" prop="component" v-if="permissionForm.type === 'menu'">
          <el-input v-model="permissionForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="图标" v-if="permissionForm.type !== 'button'">
          <el-input v-model="permissionForm.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="permissionForm.sort" :min="1" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据
const loading = ref(false)
const permissionList = ref([
  {
    id: 1,
    name: '系统管理',
    code: 'system',
    type: 'directory',
    path: '/system',
    component: '',
    icon: 'Setting',
    sort: 1,
    children: [
      {
        id: 11,
        name: '用户管理',
        code: 'system:user',
        type: 'menu',
        path: '/system/user',
        component: 'system/user/index',
        icon: 'User',
        sort: 1,
        children: [
          {
            id: 111,
            name: '用户查询',
            code: 'system:user:query',
            type: 'button',
            path: '',
            component: '',
            icon: '',
            sort: 1
          },
          {
            id: 112,
            name: '用户新增',
            code: 'system:user:add',
            type: 'button',
            path: '',
            component: '',
            icon: '',
            sort: 2
          },
          {
            id: 113,
            name: '用户修改',
            code: 'system:user:edit',
            type: 'button',
            path: '',
            component: '',
            icon: '',
            sort: 3
          },
          {
            id: 114,
            name: '用户删除',
            code: 'system:user:remove',
            type: 'button',
            path: '',
            component: '',
            icon: '',
            sort: 4
          }
        ]
      },
      {
        id: 12,
        name: '角色管理',
        code: 'system:role',
        type: 'menu',
        path: '/system/role',
        component: 'system/role/index',
        icon: 'UserFilled',
        sort: 2,
        children: [
          {
            id: 121,
            name: '角色查询',
            code: 'system:role:query',
            type: 'button',
            path: '',
            component: '',
            icon: '',
            sort: 1
          },
          {
            id: 122,
            name: '角色新增',
            code: 'system:role:add',
            type: 'button',
            path: '',
            component: '',
            icon: '',
            sort: 2
          }
        ]
      }
    ]
  },
  {
    id: 2,
    name: '系统监控',
    code: 'monitor',
    type: 'directory',
    path: '/monitor',
    component: '',
    icon: 'Monitor',
    sort: 2,
    children: [
      {
        id: 21,
        name: '在线用户',
        code: 'monitor:online',
        type: 'menu',
        path: '/monitor/online',
        component: 'monitor/online/index',
        icon: 'UserFilled',
        sort: 1
      },
      {
        id: 22,
        name: '服务监控',
        code: 'monitor:server',
        type: 'menu',
        path: '/monitor/server',
        component: 'monitor/server/index',
        icon: 'Platform',
        sort: 2
      }
    ]
  }
])

// 表单对话框
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit' | 'addChild'>('add')
const permissionForm = reactive({
  id: 0,
  parentId: null as number | null,
  name: '',
  code: '',
  type: 'menu',
  path: '',
  component: '',
  icon: '',
  sort: 1
})
const permissionFormRef = ref()

const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  path: [
    { required: true, message: '请输入路径', trigger: 'blur' }
  ],
  component: [
    { required: true, message: '请输入组件路径', trigger: 'blur' }
  ]
}

// 计算属性
const permissionOptions = computed(() => {
  const options = JSON.parse(JSON.stringify(permissionList.value))
  // 过滤掉按钮类型，因为按钮不能作为父级
  const filterButtons = (items: any[]) => {
    return items.map(item => {
      const newItem = { ...item }
      if (newItem.children && newItem.children.length > 0) {
        newItem.children = filterButtons(newItem.children.filter(child => child.type !== 'button'))
      }
      return newItem
    })
  }
  return filterButtons(options)
})

const getDialogTitle = () => {
  if (dialogType.value === 'add') return '添加权限'
  if (dialogType.value === 'edit') return '编辑权限'
  return '添加子权限'
}

// 方法
const fetchData = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const resetForm = () => {
  permissionForm.id = 0
  permissionForm.parentId = null
  permissionForm.name = ''
  permissionForm.code = ''
  permissionForm.type = 'menu'
  permissionForm.path = ''
  permissionForm.component = ''
  permissionForm.icon = ''
  permissionForm.sort = 1
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  resetForm()
  Object.assign(permissionForm, row)
  dialogVisible.value = true
}

const handleAddChild = (row: any) => {
  dialogType.value = 'addChild'
  resetForm()
  permissionForm.parentId = row.id
  // 如果父级是目录，则子级默认为菜单
  if (row.type === 'directory') {
    permissionForm.type = 'menu'
  }
  // 如果父级是菜单，则子级默认为按钮
  else if (row.type === 'menu') {
    permissionForm.type = 'button'
  }
  dialogVisible.value = true
}

const handleDelete = (row: any) => {
  // 如果有子权限，不允许删除
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该权限下有子权限，不能删除')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除权限 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {})
}

const submitForm = async () => {
  if (!permissionFormRef.value) return
  
  await permissionFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 模拟API请求
      setTimeout(() => {
        if (dialogType.value === 'add') {
          ElMessage.success('添加成功')
        } else if (dialogType.value === 'edit') {
          ElMessage.success('更新成功')
        } else {
          ElMessage.success('添加子权限成功')
        }
        dialogVisible.value = false
        fetchData()
      }, 500)
    }
  })
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.permission-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>